<template>
  <el-card class="box-card">
    <template #header>
      <div class="card-header">
        <span>宣讲订单评价</span>
      </div>
    </template>
    
    <div class="search-form">
      <el-form :inline="true" :model="formInline" class="demo-form-inline">
        <el-form-item>
          <el-input v-model="formInline.courseName" placeholder="请输入课程名称" clearable @keyup.enter="onSubmit"></el-input>
        </el-form-item>
        <el-form-item>
          <el-input v-model="formInline.createUserName" placeholder="请输入评价人姓名" clearable @keyup.enter="onSubmit"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onSubmit">
            <el-icon>
              <Search />
            </el-icon>
          </el-button>
        </el-form-item>
      </el-form>
      <div>
        <el-button type="primary" @click="evaluateApprovals">批量审核</el-button>
      </div>
    </div>

    <div class="table-data" v-loading="loading">
      <el-table
        :data="evaluateData"
        stripe
        borderresizable
        highlight-hover-row
        show-overflow
        keep-source
        scrollbar-always-on
        ref="evaluateTableRef"
      >
        <el-table-column type="selection" width="55" :selectable="changeSelectable"/>
        <el-table-column
          v-for="(tableItem, tableIndex) in evaluateTableColumns" :key="tableIndex"
          :prop="tableItem.field"
          :label="tableItem.label"
          :min-width="tableItem.minWidth"
          :formatter="tableItem.formatter"
          show-overflow-tooltip
        ></el-table-column>
        <el-table-column
          fixed="right"
          field="opera"
          label="操作"
          min-width="120"
        >
          <template #default="{ row }">
            <el-button
              type="warning"
              link
              @click="evaluateDetail(row)"
            >查看</el-button>
            <el-button
              type="success"
              link
              @click="evaluateApproval(row)"
              v-if="isFillingSystem && row.evaluateType == 1"
            >审核</el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="table-page">
        <el-pagination background layout="prev, pager, next" :total="dataTotal" :page-size="pageSize" :current-page="currentPage" @current-change="currentChange" />
      </div>
    </div>

    <approval-dialog v-model:visible="dialogVisible" @approvalChange="approvalChange" />
  </el-card>
</template>

<script>
export default { name: "backendPublicizeEvaluate" }
</script>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue';
import { useRouter } from 'vue-router'
import { Search } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import approvalDialog from "@/components/backend/approval.vue"
import { http } from '@/utils/http/index';
import { dateFormatter, checkStatusFormatter } from "@/utils/backend.js"
import { ContentTypeEnum } from '@/enums/httpEnum';
import { useAuthStore } from '@/stores/modules/auth.js';
import approvalVue from '../../../../components/backend/approval.vue';

/* 路由 */
const route = useRouter();

/* 用户信息 */
const authStore = useAuthStore()

onMounted(() => {
  onSubmit()
})

/* 当前用户是否为最高级的系统管理员 */
const isFillingSystem = computed(() => {
  let actions = authStore.userInfo.actions
  if(!actions) return
  const find = actions.find(item => item.id == '4')
  return find ? true : false
})

/* 搜索表单 */
const formInline = ref({
  region: "",
  date: "",
})

/* 分页 */
const dataTotal = ref(0)
const pageSize = ref(10)
const currentPage = ref(1)

if(route.currentRoute.value.query.currentPage) {
  currentPage.value = Number(route.currentRoute.value.query.currentPage)
}

/* 切换页码方法 */
const currentChange = (val) => {
  currentPage.value = val
  onSubmit()
}

/* 表格数据加载动画 */
const loading = ref(false)

/* 表格 */
const evaluateTableRef = ref(null)

/* 表格数据 */
const evaluateData = ref([])

/* 是否推荐字段过滤数值 */
const courseTypeFormatter = (row, column, cellValue) => {
  return cellValue == 0 ? '未审核' : cellValue == 1 ? '审核通过' : cellValue == -1 ? '审核未通过' : ''
}

/* 表格字段 */
const evaluateTableColumns = reactive([
  { field: "courseName", label: "课程名称", minWidth: "250" },
  { field: "createUserName", label: "评价人", minWidth: "120" },
  { field: "mark", label: "打分", minWidth: "120" },
  { field: "preachEvaluate_Qusetions", label: "评价项", minWidth: "250" },
  { field: "content", label: "评价内容", minWidth: "250" },
  { field: "checkStatus", label: "审核状态", minWidth: "120", formatter: courseTypeFormatter },
])

/* 表格复选框禁用 */
const changeSelectable = (row, index) => {
  return row.evaluateType == '1'
}

/* 列表筛选 */
const onSubmit = () => {
  loading.value = true
  let params = {
    pageIndex: currentPage.value,
    pageSize: pageSize.value,
  }
  let dfi = {
    Logic: 0,
    Filters: []
  }

  for (let k in formInline.value){
    if(formInline.value[k]){
      dfi.Filters.push({
        Field: k,
        Operator: 0,
        Value: formInline.value[k]
      })
    }
  }

  if(dfi.Filters.length){
    params.dfi = dfi
  }
  http.$POST("/PreachM/GetPreachEvaluateInfoList", params).then(res => {
    loading.value = false
    if (res.isError) return
    evaluateData.value = res.result.dataLst
    dataTotal.value = res.result.countAll
  }).catch(err => {
    loading.value = false
    ElMessage.warning("查询失败，请重试")
  })
}

/* 点击查看详情 */
const evaluateDetail = (row) => {
  let { href } = route.resolve({
    path: "/backend/publicize-evaluate/detail",
    query: { id: row.id, currentPage: currentPage.value }
  })
  window.open(href, "_blank")
}

/* 审核弹窗 */
const dialogVisible = ref(false)

/* 审核类型，单条或多选审核 */
const approvalType = ref("")

/* 当前列数据 */
const currentColumn = ref({})

/* 审核 */
const evaluateApproval = (row) => {
  dialogVisible.value = true
  currentColumn.value = row
  approvalType.value = "single"
}

/* 批量审核 */
const evaluateApprovals = () => {
  let checkList = evaluateTableRef.value.getSelectionRows()
  if(!checkList.length){
    ElMessage.warning("请先选择要进行操作的数据")
    return 
  }
  dialogVisible.value = true
  approvalType.value = "multiple"
}

/* 提交审核回调 */
const approvalChange = (approvalForm) => {
  if(approvalType.value == "single") {
    let params = {}
    if(approvalForm.approval == '1'){
      params = {
        id: currentColumn.value.id,
        checkStatus: 1
      }
    } else {
      params = {
        id: currentColumn.value.id,
        checkStatus: -1
      }
    }
    changeCheckStatus(params)
  } else {
    let params = []
    let checkList = evaluateTableRef.value.getSelectionRows()

    checkList.forEach((item) => {
      if(approvalForm.approval == '1') {
        params.push({
          id: item.id,
          authToken: authStore.auth_token,
          checkStatus: 1
        })
      } else {
        params.push({
          id: item.id,
          authToken: authStore.auth_token,
          checkStatus: -1
        })
      }
    })
    multipleChangeCheckStatus(params)
  }
  
}

/* 单个更改状态值 */
const changeCheckStatus = (params) => {
  http.$POST("/PreachM/AddOrUpdatePreachEvaluateInfo", {...params}, { headers: { 'Content-Type': ContentTypeEnum.FORM_DATA } }).then(res => {
    if (res.IsError) {
      ElMessage.warning('操作失败');
    }else{
      ElMessage.success('操作成功');
      onSubmit()
    }
  }).catch(err => {
    ElMessage.warning('操作失败');
  })
}

/* 多个更改状态值 */
const multipleChangeCheckStatus = (params) => {
  http.$POST("/PreachM/AddOrUpdatePreachEvaluateList", params).then(res => {
    if(res.IsError) {
      ElMessage.warning('操作失败');
    }else{
      ElMessage.success('操作成功');
      evaluateTableRef.value.clearSelection()
      onSubmit()
    }
  }).catch(err => {
    ElMessage.warning('操作失败');
  })
}
</script>

<style lang='scss' scoped>
@import "@/assets/styles/backendElement.scss";
</style>